package com.febers.ihealth.utils

import com.febers.ihealth.MyApp
import com.febers.ihealth.entity.UserBean
import org.json.JSONObject
import java.io.File

object IOUtil {

    fun saveUser(user: UserBean) {
        Thread {
            val jsonObject = JSONObject().apply {
                put("name", user.name)
                put("pw", user.pw)
                put("age", user.age)
                put("male", user.male)
                put("preg", user.preg)
                put("height", user.height)
                put("weight", user.weight)
                put("temp", user.temp)
                put("heart", user.heart)
                put("pressure", user.pressure)
                put("flutimes", user.fluTimes)
            }
            val string = jsonObject.toString()
            File(MyApp.context().cacheDir.path + "/user.txt").writeText(string)
        }.start()
    }

    fun readUser(): UserBean {
        val user = UserBean()
        try {
            val string: String = File(MyApp.context().cacheDir.path + "/user.txt").readText()
            val o = JSONObject(string)
            user.name = o.getString("name")
            user.age = o.getString("age")
            user.pw = o.getString("pw")
            user.male = o.getBoolean("male")
            user.preg = o.getBoolean("preg")
            user.height = o.getString("height")
            user.weight = o.getString("weight")
            user.temp = o.getString("temp")
            user.heart = o.getString("heart")
            user.pressure = o.getString("pressure")
            user.fluTimes = o.getString("flutimes")
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return user
    }

    fun clearUser() {
        try {
            File(MyApp.context().cacheDir.path + "/user.txt").delete()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}